package main

import (
	"fmt"
	"log"
	"time"

	"wmp/protocol"
)

func main() {
	// Start manager
	manager, err := protocol.NewManager(":8080")
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Manager created and listening on :8080")
	go manager.Start()

	// Start worker
	worker := protocol.NewWorker([]string{":8080"}, processJob)
	if err := worker.Connect(); err != nil {
		log.Fatal(err)
	}
	log.Println("Worker connected to manager")
	defer worker.Close()

	if err := worker.SendReady(); err != nil {
		log.Fatal(err)
	}
	log.Println("Worker sent READY message")

	go worker.HandleMessages()

	// Add some jobs
	log.Println("Adding jobs to the manager")
	for i := 0; i < 5; i++ {
		job := &protocol.Job{
			ID:      fmt.Sprintf("job-%d", i),
			Payload: []byte(fmt.Sprintf("Job payload %d", i)),
		}
		manager.AddJob(job)
		log.Printf("Added job: %s", job.ID)
	}

	// Wait for jobs to be processed
	log.Println("Waiting for jobs to be processed")
	time.Sleep(5 * time.Second)

	fmt.Println("Gearman Protocol demonstration completed")
}

func processJob(payload []byte) ([]byte, error) {
	log.Printf("Processing job with payload: %s", payload)
	// Simulate job processing
	time.Sleep(1 * time.Second)
	result := []byte(fmt.Sprintf("Processed: %s", payload))
	log.Printf("Job processed, result: %s", result)
	return result, nil
}
